import { Rules } from "async-validator";
import { Context } from "koa";
import validate from "../utils/validate";
import response from "../utils/response";
import SourceService from "../service/SourceService";

class Index {
    async add(ctx: Context){
        const rules: Rules = {
            name: [
                {
                    type: 'string',
                    required: true,
                    message: '项目名称不能为空',
                }
            ],
            source: [
                {
                    type: 'string',
                    required: true,
                    message: 'git仓库不能为空',
                },
            ],
            port: [
                {
                    type: 'string',
                    required: true,
                    message: '端口不能为空',
                },
            ],
        }

        interface Source {
            name: string,
            git: string,
            port: string
        }

        const { data, error } = await validate<Source>(ctx, rules)

        if(error !== null) return response.error(ctx, error.message)

        const admin = await SourceService.getSourceByName(data.name);
        if(admin !== null){
            return response.error(ctx, '项目名已经存在')
        }

        const row = await SourceService.addSource(data);

        if(row.id > 0){
            return response.success(ctx, '添加成功');
        }else{
            return response.error(ctx, '添加失败');
        }
    }
}

export default new Index